Page({
  data: {
    loanAmount: '',          // 贷款金额
    loanTerm: '',            // 贷款期限（月）
    interestRate: '3.1',     // 年利率
    repaymentMethod: '1',     // 还款方式：1-等额本息，2-等额本金
    calculationRecords: []
  },
  // 页面显示时获取之前保存的计算记录
  onShow: function () {
    // 获取之前保存的数据
    let savedData = wx.getStorageSync('loanCalculationResult') || [];
    if (typeof savedData!== 'object' ||!Array.isArray(savedData)) {
      savedData = [];
    }
    const savedDataJson = JSON.stringify(savedData);
    console.log('savedData 的 JSON 格式:', savedDataJson);
    this.setData({
      calculationRecords: savedData
    });
  },
  viewRecord(e) {
    const index = e.currentTarget.dataset.index;
    const record = this.data.calculationRecords[index];
    // 这里跳转到 resultView 页面展示结果集
    wx.navigateTo({
      url: `/pages/resultView/resultView?code=${record.code}&params=${JSON.stringify(record.params)}&result=${JSON.stringify(record.result)}`
    });
  },


  // 输入框变化事件
  handleInputChange: function(e) {
    const { field } = e.currentTarget.dataset;
    let value = e.detail.value;
    
    // 验证输入范围
    if (field === 'loanTerm' && value > 360) {
      value = 360;
      wx.showToast({
        title: '贷款期限最长360个月',
        icon: 'none'
      });
    }
    
    this.setData({
      [field]: value
    });
  },

  // 还款方式切换
  handleRepaymentChange: function(e) {
    this.setData({
      repaymentMethod: e.detail.value
    });
  },

  // 计算贷款并跳转到结果页
  calculateLoan: function() {
    const { loanAmount, loanTerm, interestRate, repaymentMethod } = this.data;
    
    if (!loanAmount || !loanTerm || !interestRate) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    
    const principal = parseFloat(loanAmount);
    const months = parseInt(loanTerm);
    const annualRate = parseFloat(interestRate);
    
    if (principal <= 0 || months <= 0 || annualRate <= 0) {
      wx.showToast({
        title: '请输入有效数值',
        icon: 'none'
      });
      return;
    }
    
    let result;
    if (repaymentMethod === '1') {
      result = this.calculateEqualPayment(principal, months, annualRate);
    } else {
      result = this.calculateEqualPrincipal(principal, months, annualRate);
    }
    
    // 跳转到结果页，并传递计算结果
    wx.navigateTo({
      url: `/pages/result/result?repaymentMethod=${repaymentMethod}`,
      success: function(res) {
        res.eventChannel.emit('acceptData', {
          result: result,
          params: {
            loanAmount: principal,
            loanTerm: months,
            interestRate: annualRate,
            repaymentMethod: repaymentMethod
          }
        });
      }
    });
  },

  // 等额本息计算
  calculateEqualPayment: function(principal, months, annualRate) {
    const monthlyRate = annualRate / 100 / 12;
    const monthlyPayment = principal * monthlyRate * Math.pow(1 + monthlyRate, months) / 
                          (Math.pow(1 + monthlyRate, months) - 1);
    const totalPayment = monthlyPayment * months;
    const totalInterest = totalPayment - principal;
    
    // 生成还款明细
    let paymentDetails = [];
    let remainingPrincipal = principal;
    
    for (let i = 1; i <= months; i++) {
      const interest = remainingPrincipal * monthlyRate;
      const principalPayment = monthlyPayment - interest;
      remainingPrincipal -= principalPayment;
      
      // 处理最后一个月可能出现的精度问题
      if (i === months) {
        remainingPrincipal = 0;
      }
      
      paymentDetails.push({
        month: i,
        monthlyPayment: monthlyPayment.toFixed(2),
        principal: principalPayment.toFixed(2),
        interest: interest.toFixed(2),
        remaining: remainingPrincipal > 0 ? remainingPrincipal.toFixed(2) : '0.00'
      });
    }
    
    return {
      monthlyPayment: monthlyPayment.toFixed(2),
      totalPayment: totalPayment.toFixed(2),
      totalInterest: totalInterest.toFixed(2),
      paymentDetails: paymentDetails
    };
  },

  // 等额本金计算
  calculateEqualPrincipal: function(principal, months, annualRate) {
    const monthlyRate = annualRate / 100 / 12;
    const principalPayment = principal / months;
    let totalInterest = 0;
    let remainingPrincipal = principal;
    let paymentDetails = [];
    
    for (let i = 1; i <= months; i++) {
      const interest = remainingPrincipal * monthlyRate;
      const monthlyPayment = principalPayment + interest;
      totalInterest += interest;
      remainingPrincipal -= principalPayment;
      
      // 处理最后一个月可能出现的精度问题
      if (i === months) {
        remainingPrincipal = 0;
      }
      
      paymentDetails.push({
        month: i,
        monthlyPayment: monthlyPayment.toFixed(2),
        principal: principalPayment.toFixed(2),
        interest: interest.toFixed(2),
        remaining: remainingPrincipal > 0 ? remainingPrincipal.toFixed(2) : '0.00'
      });
    }
    
    return {
      firstMonthPayment: (principalPayment + principal * monthlyRate).toFixed(2),
      lastMonthPayment: (principalPayment + principalPayment * monthlyRate).toFixed(2),
      totalPayment: (principal + totalInterest).toFixed(2),
      totalInterest: totalInterest.toFixed(2),
      paymentDetails: paymentDetails
    };
  }
})